#include <QFile>
#include <QMessageBox>

#include "words.h"

Words::Words()
{
    m_webPage = NULL;
}

void Words::processXML()
{
    /* We'll parse the example.xml */
    //QFile* file = new QFile("/home/florina/work/trunk/translations/words_merriam.xml");
    QFile* file = new QFile("/home/florina/work/Dictionary/trunk/translations/words_merriam.xml");
    /* If we can't open it, let's show an error message. */
    if (!file->open(QIODevice::ReadOnly | QIODevice::Text)) {
       qDebug()<<"Can't open file";
        return;
    }
    QXmlStreamReader xml(file);
    while(!xml.atEnd() && !xml.hasError())
    {
        /* Read next element.*/
        QXmlStreamReader::TokenType token = xml.readNext();
        /* If token is just StartDocument, we'll go to next.*/
        if(token == QXmlStreamReader::StartDocument)
        {
            continue;
        }
        /* If token is StartElement, we'll see if we can read it.*/
        if(token == QXmlStreamReader::StartElement)
        {
            /* If it's named persons, we'll go to the next.*/
            if(xml.name() == "words")
            {
                continue;
            }
            /* If it's named person, we'll dig the information from there.*/
            if(xml.name() == "word")
            {
                m_words.append(parseWord(xml));
            }
        }
    }
    /* Error handling. */
    if(xml.hasError())
        qDebug()<<"QXSRExample::parseXML"<<xml.errorString();
    xml.clear();
    delete file;
}

QMap<QString, QString> Words::parseWord(QXmlStreamReader &xml)
{
    QMap<QString, QString> word;
    /* Let's check that we're really getting a person. */
    if(xml.tokenType() != QXmlStreamReader::StartElement && xml.name() == "word")
    {
        return word;
    }
    QXmlStreamAttributes attributes = xml.attributes();
    if(attributes.hasAttribute("id"))
    {
       word["id"] = attributes.value("id").toString();
    }
    xml.readNext();

    while(!(xml.tokenType() == QXmlStreamReader::EndElement && xml.name() == "word"))
    {
        if(xml.tokenType() == QXmlStreamReader::StartElement)
        {
            if(xml.name() == "name")
                this->addElementDataToMap(xml, word);
            if(xml.name() == "definition")
                this->addElementDataToMap(xml, word);
        }
        /* ...and next... */
        xml.readNext();
    }
    return word;
}

void Words::addElementDataToMap(QXmlStreamReader &xml, QMap<QString, QString> &word)
{
    /* We need a start element, like <foo> */
       if(xml.tokenType() != QXmlStreamReader::StartElement)
       {
           return;
       }
       /* Let's read the name... */
       QString elementName = xml.name().toString();
       /* ...go to the next. */
       xml.readNext();
       /*
        * This elements needs to contain Characters so we know it's
        * actually data, if it's not we'll leave.
        */
       if(xml.tokenType() != QXmlStreamReader::Characters)
       {
           return;
       }
       /* Now we can add it to the map.*/
       word.insert(elementName, xml.text().toString());
       //qDebug()<<elementName<<":"<<xml.text().toString();
}

void Words::searchWord(const QString &word)
{
    qDebug()<<"search for:"<<word;
    QString str_translation = findWordInList(word);
    emit updateTranslation(QVariant(str_translation));
}

QString Words::findWordInList(const QString word)
{
    qDebug()<<"list size="<<m_words.size();
    for (int i = 0; i < m_words.size(); i++)
    {
        qDebug()<<(m_words.at(i))["name"];
        if (m_words.at(i)["name"] == word)
        {
            qDebug()<<"found translation";
            return m_words.at(i)["definition"];
        }
    }
    qDebug()<<"can't found translation";
    return "";
}

void Words::removeBackground(QString &definition)
{
    QString back       = "background: url(/images/lma_thes.jpg)";
    int start_idx_back = definition.indexOf(back);
    int end_idx_back   = definition.indexOf(";", start_idx_back+1);
    definition         = definition.remove(start_idx_back, end_idx_back-start_idx_back);

    back           = "background: url(/images/lma_span.jpg)";
    start_idx_back = definition.indexOf(back);
    end_idx_back   = definition.indexOf(";", start_idx_back+1);
    definition     = definition.remove(start_idx_back, end_idx_back-start_idx_back);

    back           = "background: url(/images/lma_enc.jpg)";
    start_idx_back = definition.indexOf(back);
    end_idx_back   = definition.indexOf(";", start_idx_back+1);
    definition     = definition.remove(start_idx_back, end_idx_back-start_idx_back);
}

void Words::removeImg(QString &definition)
{
    QString img       = "img ";
    int start_idx_img = definition.indexOf(img);
    int end_idx_img   = definition.indexOf(">", start_idx_img+1);
    definition        = definition.remove(start_idx_img, end_idx_img-start_idx_img);

    if( definition.indexOf(img) != -1)
        removeImg(definition);
}

void Words::searchOnWeb(const QString &word)
{
    if (m_webPage != NULL)
        delete m_webPage;
    m_webPage =  new QWebPage();
    connect(m_webPage->currentFrame (), SIGNAL(loadFinished(bool)), this, SLOT(parsePage(bool)));

    qDebug()<<"search word:"<<word;
    QString  whatGet = "http://www.merriam-webster.com/dictionary/"+word;
    m_webPage->mainFrame()->setUrl(whatGet);

}

void Words::parsePage(bool load)
{
    if(!load)
    {
        qDebug()<<"nu a facut load";
        return;
    }
    else
        qDebug()<<" A facut load page";

    QString data;
    QString wordDefinition;
    QString keyStartDefinition = "<span>Definition of <em>";
    data = m_webPage->currentFrame ()->toHtml().toLatin1();

    int index_definition = data.indexOf(keyStartDefinition);
    wordDefinition       = data.mid(index_definition+keyStartDefinition.length());
    index_definition     = wordDefinition.indexOf(keyStartDefinition);
    wordDefinition.remove( index_definition, wordDefinition.length() - index_definition );

   // parseHtml(data, wordDefinition);
    removeImg(wordDefinition);
    removeBackground(wordDefinition);
    emit updateTranslation(QVariant("<html>" + wordDefinition + "</html>"));

}
